package com.zachary.zbigdata.brank.spark.yarn;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: zachary
 * Date: 14-5-2
 * Time: 下午4:43
 * PC：ubuntu'IDEA in home
 */
public class ListTest {
    public static void main(String[] args) throws Exception {

        SparkConf sparkConf = new SparkConf();
        sparkConf.setAppName("listTest");
        //使用yarn模式提交
        sparkConf.setMaster("yarn-client");

        JavaSparkContext sc = new JavaSparkContext(sparkConf);

        List<String> listA = new ArrayList<String>();

        listA.add("a");
        listA.add("a");
        listA.add("b");
        listA.add("b");
        listA.add("b");
        listA.add("c");
        listA.add("d");

        JavaRDD<String> letterA = sc.parallelize(listA);

        JavaPairRDD<String, Integer> letterB = letterA.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<String, Integer>(s, 1);
            }
        });

        letterB = letterB.reduceByKey(new Function2<Integer, Integer, Integer>() {
            public Integer call(Integer i1, Integer i2) {
                return i1 + i2;
            }
        });

        //颠倒顺序
        JavaPairRDD<Integer, String> letterC = letterB.mapToPair(new PairFunction<Tuple2<String, Integer>, Integer, String>() {
            @Override
            public Tuple2<Integer, String> call(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
                return new Tuple2<Integer, String>(stringIntegerTuple2._2, stringIntegerTuple2._1);
            }
        });

        JavaPairRDD<Integer, Iterable<String>> letterD = letterC.groupByKey();
//        //false说明是降序
        JavaPairRDD<Integer, Iterable<String>> letterE = letterD.sortByKey(false);

        System.out.println("========" + letterE.collect());

        System.exit(0);
    }
}